#include "..\stdafx.h"
#include "sqlite.h"
#include "DbProxy.h"
#include <afxconv.h>

int CDbProxy::Open(CString dbFile) {
	int result = SQLite::Open(dbFile);
	if (result == SQLITE_OK) {
		m_isValid = TRUE;
	}

	return result;
} // CDbProxy::Open()

int CDbProxy::Execute(CString query) 
{
	if (!isValid())	return 0;

	int result = SQLite::Execute(query);
	if (result != SQLITE_OK) {
		CString error;
		error.Format(_T("SQLite error: %s"), CA2W(this->m_pLastError));
		::AfxMessageBox(error, MB_OK | MB_ICONEXCLAMATION);
	}
	return result;	
}

BOOL CDbProxy::isValid()
{
	if (!m_isValid) {
		if (!m_isValidMsgDisplayed) {
		  ::AfxMessageBox(_T("No database available"), MB_OK | MB_ICONEXCLAMATION);
		  m_isValidMsgDisplayed = TRUE;
		};
		return FALSE;
	}
	return TRUE;
};

int CDbProxy::BeginTransaction()
{
	if (!m_isTransaction) {
		m_isTransaction = TRUE;
		return Execute(_T("BEGIN TRANSACTION;"));
	} else
		return 0;
}

int CDbProxy::Commit()
{
	if (m_isTransaction) {
		m_isTransaction = FALSE;
		return Execute(_T("COMMIT;"));
	} else
		return 0;
}

int CDbProxy::Rollback()
{
	if (m_isTransaction) {
		m_isTransaction = FALSE;
		return Execute(_T("ROLLBACK;"));
	} else
		return 0;
}